package com.edu.base.common.paytengjie.impl.wxjsapi;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.edu.base.common.HttpSSLUtil;
import com.edu.base.common.HttpUtil;
import com.edu.base.common.paytengjie.Pay;
import com.edu.base.common.paytengjie.bean.NotifyResponse;
import com.edu.base.common.paytengjie.bean.PayRequest;
import com.edu.base.common.paytengjie.bean.PayResponse;
import com.edu.base.common.paytengjie.bean.RefundRequest;
import com.edu.base.common.paytengjie.bean.RefundResponse;
import com.edu.base.common.paytengjie.bean.Response;
import com.edu.base.common.paytengjie.bean.TransferRequest;
import com.edu.base.common.paytengjie.bean.TransferResponse;
import com.edu.base.common.paytengjie.impl.wxapp.utils.WxSDKConfig;
import com.edu.base.common.paytengjie.impl.wxapp.utils.WxUtil;
import com.edu.base.common.paytengjie.impl.wxapp.utils.XMLUtil;


 
/**
 * 微信支付-小程序
 * @author ljf
 *
 */
@Component
public class WxPayJs extends Pay {
	
	/**
	 * 支付
	 */
	//@SuppressWarnings("unchecked")
	//@Override
//	public PayResponse toPay(PayRequest request){
//			PayResponse response = new PayResponse();
//			String nonceStr = WxUtil.getNonceStr();//随机支付串
//	        ////调用微信支付 ,得到请求的XML格式
//	        String requestXML = WxUtil.getRequestXml(payMap(request,nonceStr));  
//	        logger.info("微信小程序支付开始,请求参数【"+requestXML+"】");
//	        //发起统一下单请求，返回结果
//	        String resXml = HttpUtil.postData(WxSDKConfig.getPayUrl(), requestXML);  
//	        logger.info("微信小程序支付完成,返回参数【"+resXml+"】");
//	        //解析xml成map  
//	        Map<String, String> xmlToMap = new HashMap<String, String>();  
//	        try {
//	        	xmlToMap = XMLUtil.doXMLParse(resXml);
//			} catch (Exception e) {
//				logger.error("微信支付-小程序，解析返回接口异常：",e);
//				response.setErrorCode(Response.IS_FAIL);
//				response.setErrorMsg("微信支付-小程序，解析返回接口异常");
//				return response;
//			} 
//	        //获取返回参数，过滤空  TreeMap
//	        SortedMap<Object,Object> packageParams = WxUtil.getMapParams(xmlToMap);
//	        //验证返回码是否成功
//	        if(!"SUCCESS".equals(packageParams.get("return_code"))){
//	        	response.setErrorCode((String)packageParams.get("return_code"));
//	        	response.setErrorMsg((String)packageParams.get("return_msg"));
//	        	 return response;
//	        }
//	        //获取统一订单号
//	        String prepay_id = (String)packageParams.get("prepay_id"); 
//	        //将Map返回前端，可打开微信支付页面
//	        Map<String, Object> map = new HashMap<String, Object>();
//	        map.put("appid", WxSDKConfig.getJsAppId()); //应用ID
//	        map.put("prepayid", prepay_id);	//预支付交易会话ID
//	        map.put("nonceStr", nonceStr);	//随机字符串
//	        map.put("timeStamp", new Date().getTime()/1000+"");	//时间戳
//	        map.put("sign", getSign(prepay_id,nonceStr));//签名
//	        response.setParamsMap(map);
//	        response.setErrorCode(Response.IS_SUCCESS);
//	        return response;
//	};
	
	
	/**
	 * 退款
	 */
	//@Override
//	public RefundResponse toRefund(RefundRequest request) {
//		RefundResponse response = new RefundResponse();
//		try{
//			String nonceStr = WxUtil.getNonceStr();//随机支付串
//	        //封装为xml格式
//	        String requestXML = WxUtil.getRequestXml(refundMap(request,nonceStr));  
//	        logger.info("微信小程序退款开始,请求参数【"+requestXML+"】");
//	        //发起退款，并返回结果
//	        String resXml = HttpSSLUtil.httpSSL(WxSDKConfig.getRefundUrl(), requestXML).toString();
//	        logger.info("微信小程序退款完成,返回参数【"+resXml+"】");
//	        //解析xml结果为map
//	        Map map = XMLUtil.doXMLParse(resXml); 
//	        //判断退款结果返回值
//	        if("SUCCESS".equals(map.get("result_code"))){
//	        	response.setErrorCode(Response.IS_SUCCESS);
//	        }else{
//	        	response.setErrorCode(map.get("err_code")==null?"":map.get("err_code").toString());
//	        	response.setErrorMsg(map.get("err_code_des")==null?"":map.get("err_code_des").toString());
//	        }
//		}catch(Exception e){
//			logger.error("微信退款小程序异常",e);
//			response.setErrorCode(Response.IS_FAIL);
//			response.setErrorMsg("微信退款小程序异常");
//		}
//		return response;
//	}
	
	/**
	 * 转账
	 */
	@Override
	public TransferResponse toTransfer(TransferRequest request) {
		return null;
	}
	
	
	/**
	 * 异步通知处理
	 */
	//@Override
//	public NotifyResponse asyncHandle(HttpServletRequest request) {
//		NotifyResponse  notifyResponse = new NotifyResponse();
//		try {
//			//解析微信回调参数
//			SortedMap<Object,Object> packageParams = WxUtil.getWxPostParams(request);
//			//校验签名是否通过,默认通过
//			if(!WxUtil.isTenpaySign("UTF-8", packageParams,WxSDKConfig.getApiKey())){
//				 notifyResponse.setErrorCode(Response.IS_FAIL);
//				 notifyResponse.setErrorMsg("微信异步通知小程序【签名错误】");
//			}else if(!"SUCCESS".equals(packageParams.get("result_code"))){
//				 notifyResponse.setErrorCode(packageParams.get("err_code").toString());
//				 notifyResponse.setErrorMsg(packageParams.get("err_code_des").toString());
//			}else{
//				//商户订单号
//				notifyResponse.setOrderId(packageParams.get("out_trade_no").toString());
//				//第三方交易号，微信/支付宝
//				notifyResponse.setTradeNo(packageParams.get("transaction_id").toString());
//				//买家账号 ,买家支付宝账号/openId
//				notifyResponse.setBuyerId(packageParams.get("openid").toString());
//				//通知时间
//				notifyResponse.setNotifyTime(packageParams.get("time_end").toString());
//				//卖家账号 ,卖家支付宝账号/appid
//				notifyResponse.setSellerId(packageParams.get("appid").toString());
//				//订单金额
//				notifyResponse.setTotalAmount(WxUtil.changeF2Y(packageParams.get("total_fee").toString()));
//				System.out.println("----------微信返回的支付金额（元）-------------------:"+notifyResponse.getTotalAmount());
//
//				
//				notifyResponse.setErrorCode(Response.IS_SUCCESS);
//			}
//
//		} catch (Exception e) {
//			logger.error("微信异步通知小程序-异常",e);
//			notifyResponse.setErrorCode(Response.IS_FAIL);
//			notifyResponse.setErrorMsg("微信异步通知小程序-异常");
//		}  
//		return notifyResponse;
//		
//	}
	
	
	/**
	 * 异步通知接口返回报文-成功
	 */
	@Override
	public String returnSuccess(){
		return "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
				+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> "; 
	}
	
	/**
	 * 异步通知接口返回报文-失败
	 */
	@Override
	public String returnFail(){
		return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
				+ "<return_msg><![CDATA[异常]]></return_msg>" + "</xml> "; 
	}

	
	/**
	 * 公共合并map
	 * @param map
	 * @return
	 */
	private SortedMap<Object,Object> combineMap(SortedMap<Object,Object> map,String nonceStr){
		map.put("appid", WxSDKConfig.getJsAppId());  //应用ID
		map.put("mch_id", WxSDKConfig.getMchId());  //商户号
		map.put("nonce_str", nonceStr);  //随机字符串
		 //签名
        String sign = makeSign(map);
        map.put("sign", sign); //签名
		return map;
	}
	
	
	/**
	 * 公共生成签名
	 * @return
	 */
	private String makeSign(SortedMap<Object,Object> map){
		return  WxUtil.createSign("UTF-8", map,WxSDKConfig.getApiKey());  
	}
	
	
	/**
	 * 支付-拼装支付map
	 */
	private SortedMap<Object,Object> payMap(PayRequest request,String nonceStr){ 
		SortedMap<Object,Object> wxParam = new TreeMap<Object,Object>(); 
		//设置参数
        wxParam.put("body", request.getBody());  //商品描述
        wxParam.put("out_trade_no", request.getOrderId());  //商户订单号
        wxParam.put("openid", request.getOpenidJs());//小程序openid
        wxParam.put("total_fee", (int)(new BigDecimal(request.getTotalAmount()).doubleValue()*100)+""); //单位：分  总金额 
        wxParam.put("spbill_create_ip", request.getClientIp());  //终端IP
        wxParam.put("notify_url", request.getNotifyUrl());  //通知地址
        wxParam.put("trade_type", "JSAPI"); //交易类型
		return combineMap(wxParam,nonceStr);
	}
	
 
	
	/**
	 * 支付-获取返回前端的加密签名
	 * @param prepay_id 统一支付id
	 * @return
	 */
	private String getSign(String prepay_id,String nonceStr){
		//APP支付参数
        SortedMap<Object,Object> resMap = new TreeMap<Object,Object>(); 
        resMap.put("appId", WxSDKConfig.getJsAppId()); //应用ID
        resMap.put("timeStamp", new Date().getTime()/1000+"");	//时间戳
        resMap.put("nonceStr", nonceStr);	//随机字符串
        resMap.put("package", "prepay_id="+prepay_id);	//扩展字段
        resMap.put("signType", "MD5");	//随机字符串
        //签名
		return makeSign(resMap);
	}
	
	
	/**
	 * 退款-拼装map
	 */
	private SortedMap<Object,Object> refundMap(RefundRequest request,String nonceStr){ 
		SortedMap<Object,Object> wxParam = new TreeMap<Object,Object>(); 
		 //封装退款参数
	    wxParam.put("transaction_id", request.getTradeNo());  //微信订单号
	    wxParam.put("out_refund_no", request.getOrderId());  //商户订单号
	    wxParam.put("total_fee", (int)(new BigDecimal(request.getTotalAmount()).doubleValue()*100)+"");  
	    wxParam.put("refund_fee", (int)(new BigDecimal(request.getRefundAmount()).doubleValue()*100)+"");  
		return combineMap(wxParam,nonceStr);
	}
	
	
	public static void main(String[] args) throws ParseException {
		Date now=new Date();
		Date start=new Date();
		Date end=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
		start=sdf.parse("2018-06-12"); 
		end=sdf.parse("2018-06-15"); 
		 
		if (now.before(end) &&  now.after(start) ){ 
			System.out.println("------------");
		} 
	}


	@Override
	public PayResponse toPay(PayRequest request) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public RefundResponse toRefund(RefundRequest request) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public NotifyResponse asyncHandle(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}
}
